package com.noob.assessment.manage.storage;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;

/**
 * @author: zhengwq
 * datetime: 2020-04-17 15:04
 * description: 文件存储管理器
 */
@Slf4j
@Component
public class StorageManager {

    /**
     * 文件存储的本地目录
     */
    @Value("${storage.folder}")
    private String storageFolder;

    @PostConstruct
    public void init() {
        File dir = new File(storageFolder);
        if (!dir.exists()) {
            boolean result = dir.mkdirs();
            if (result) {
                System.out.println("目录已创建!");
            }
        } else {
            System.out.println("目录已存在!");
        }
    }

    /**
     * 保存或更新文件(直接覆盖文件)
     *
     * @param fileName    文件名
     * @param fileContent 文件内容
     * @return 操作是否成功
     */
    public boolean saveOrUpdateFile(String fileName, String fileContent) {
        // 得到文件完整路径
        String fileFullPath = storageFolder + fileName;
        // 将\n 替换为 \r\n
        if (StringUtils.isNotBlank(fileContent)) {
            fileContent = fileContent.replaceAll("\\n", "\r\n");
        }
        try (
                BufferedInputStream bis = new BufferedInputStream(IOUtils.toInputStream(fileContent, "utf-8"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileFullPath))
        ) {
            IOUtils.copy(bis, bos);
        } catch (IOException e) {
            log.info("存储文件[{}]出错！原因:{}", fileName, e);
            return false;
        }
        return true;
    }

    /**
     * 读取文件内容
     *
     * @param fileName 文件名
     * @return 文件内容
     */
    public String readFile(String fileName) {
        // 得到文件完整路径
        String fileFullPath = storageFolder + fileName;
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileFullPath))
        ) {
            return IOUtils.toString(bis, "utf-8");
        } catch (IOException e) {
            log.info("读取文件[{}]出错！原因:{}", fileName, e);
        }
        return null;
    }

}
